package com.example.mydownloader.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mydownloader.R
import com.example.mydownloader.config.thread.MyThreadPool
import com.example.mydownloader.data.login.LoginRepository
import com.example.mydownloader.data.login.Result
import com.example.mydownloader.data.model.inputdata.LoggedInUser
import kotlinx.coroutines.launch

class LoginViewModel(private val loginRepository: LoginRepository) : ViewModel() {

    private val _loginForm = MutableLiveData<LoginFormState>()
    val loginFormState: LiveData<LoginFormState> = _loginForm

    private val _loginResult = MutableLiveData<LoginResult>()
    val loginResult: LiveData<LoginResult> = _loginResult

    private val passwordRegex =
        Regex("^(?=.*[A-Za-z])(?=.*\\d)(?=.*[\$@\$!%*#?&])[A-Za-z\\d\$@\$!%*#?&]{8,}\$")

    fun getUser(): LoggedInUser? {
        return loginRepository.user
    }

    fun login(username: String, password: String) {
        this.viewModelScope.launch(MyThreadPool.coroutineDispatcher) {
            val result = loginRepository.login(username, password)
            if (result is Result.Success) {
                _loginResult.postValue(LoginResult(success = LoggedInUserView(displayName = result.data.displayName)))
            } else {
                _loginResult.postValue(LoginResult(error = R.string.login_failed))
            }
        }
    }

    fun loginDataChanged(username: String, password: String) {
        if (!isUserNameValid(username)) {
            _loginForm.value = LoginFormState(usernameError = R.string.invalid_username)
        } else if (!isPasswordValid1(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.invalid_password1)
        } else if (!isPasswordValid2(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.invalid_password2)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

    // A placeholder username validation check
    private fun isUserNameValid(username: String): Boolean {
//        return if (username.contains('@')) {
//            Patterns.EMAIL_ADDRESS.matcher(username).matches()
//        } else {
//            username.isNotBlank()
//        }
        return username.isNotBlank()
    }

    /**
     * A placeholder password validation check
     * 长度必须大于8
     */
    private fun isPasswordValid1(password: String): Boolean {
        return password.length > 8
    }

    /**
     * A placeholder password validation check
     * 必须包含数字、字母及特殊字符(区分大小写)
     */
    private fun isPasswordValid2(password: String): Boolean {
        return password.matches(passwordRegex)
    }
}